<template>
  <div class="_wz_hiddenDangersTroubleshootAdd">
    <div style="padding: 10px 0 0 0;">
      <Form ref="riskPointDataForm" :model="riskListData" label-position="right" :label-width="100" :rules="ruleValidate">
        <FormItem label="运输企业" prop="deptUuid">
          <i-select v-model="riskListData.deptUuid" filterable placeholder="请选择运输企业" clearable  @on-change="locationFebruary">
            <Option v-for="item in subDeptList" :value="item.uuid" :key="item.uuid">{{ item.deptName }}</Option>
          </i-select>
        </FormItem>
        <FormItem label="排查类型" prop="riskPointTypeCode">
          <i-select v-model="riskListData.riskPointTypeCode" filterable placeholder="请选择排查类型" clearable :label-in-value="true" @on-change="riskPointNameFun" :disabled="!!riskListData.id">
            <Option :value="item.code" :key="item.id" v-for="item in riskPointType">{{ item.value }}</Option>
          </i-select>
        </FormItem>
        <FormItem label="排查清单" prop="riskPointUuid" v-if="!riskListData.id">
          <i-select v-model="riskListData.riskPointUuid" filterable placeholder="请选择排查清单" clearable :label-in-value="true" @on-change="riskCheckCycleFun">
            <Option :value="item.uuid" :key="item.id" v-for="item in riskPointList">{{item.riskPointName}}</Option>
          </i-select>
        </FormItem>

        <FormItem label="排查清单" prop="riskPointName" v-else>
          <i-input v-model="riskListData.riskPointName" placeholder="请选择排查清单" clearable disabled />
        </FormItem>
<!--            <FormItem label="排查周期" prop="riskCheckCycle">-->
<!--              <i-select v-model.number="riskListData.riskCheckCycle" filterable placeholder="请选择排查周期" clearable disabled>-->
<!--                <Option :value="0">不限</Option>-->
<!--                <Option :value="1">每天</Option>-->
<!--                <Option :value="2">每周</Option>-->
<!--                <Option :value="3">每旬</Option>-->
<!--                <Option :value="4">每月</Option>-->
<!--                <Option :value="5">每季</Option>-->
<!--              </i-select>-->
<!--            </FormItem>-->
        <FormItem label="排查日期" prop="riskCheckDate">
          <DatePicker type="month" v-model="riskListData.riskCheckDate" placeholder="请选择排查日期" style="width: 100%;"></DatePicker>
        </FormItem>
        <FormItem label="排查阶段" prop="riskCheckPhase">
          <i-select v-model="riskListData.riskCheckPhase" filterable placeholder="请选择排查阶段" clearable>
            <Option :value="item" :key="item" v-for="item in riskCheckPhaseList">{{ item }}</Option>
          </i-select>
        </FormItem>
        <FormItem label="排查人员" prop="riskCheckPerson">
          <i-input v-model="riskListData.riskCheckPerson" placeholder="请填写排查人员" clearable />
        </FormItem>
        <Row>
          <i-col span="12">
            <FormItem label="排查照片">
              <Upload :before-upload="riskCheckFileFun" action="" style="color: #2d8cf0;cursor: pointer;">上传排查照片
              </Upload>
              <div class="demo-upload-list">
                <viewer style="width: 100%;height: 100%;">
                  <img :src="!!riskCheckFile.url?riskCheckFile.url:'../../static/img/zwtpxd.png'" @error="public.imgDispose">
                </viewer>
              </div>
            </FormItem>
          </i-col>
          <i-col span="12">
            <FormItem label="签字照片">
              <Upload :before-upload="riskCheckSignFileFun" action="" style="color: #2d8cf0;cursor: pointer;">上传签字照片
              </Upload>
              <div class="demo-upload-list">
                <viewer style="width: 100%;height: 100%;">
                  <img :src="!!riskCheckSignFile.url?riskCheckSignFile.url:'../../static/img/zwtpxd.png'" @error="public.imgDispose">
                </viewer>
              </div>
            </FormItem>
          </i-col>
        </Row>
      </Form>
    </div>


    <div class="demo-drawer-footer" style="z-index: 99;">
      <Button style="margin-right: 8px" @click="$emit('closeFun', false)">取消</Button>
      <Button type="primary" @click="addSubmit">提交</Button>
    </div>

    <Spin size="large" fix v-if="spinShow"></Spin>

  </div>
</template>
<script>
export default {
  props: ['selectData'],//接收来自父组件的数据
  data() {
    return {
      uploadProgress: 0,//文件上传进度
      riskCheckPhaseList: [],
      spinShow: false,//本页加载
      ruleValidate: {//正则
        deptUuid: [
          {required: true, message: '请选择运输企业', trigger: 'blur'}
        ],
        riskPointTypeCode: [
          {required: true, message: '请选择排查类型', trigger: 'blur'}
        ],
        riskCheckPerson: [
          {required: true, message: '请填写排查人员', trigger: 'blur'}
        ],
        riskPointUuid: [
          {required: true, message: '请选择排查清单', trigger: 'blur'}
        ],
        riskCheckDate: [
          {type: "date", required: true, message: "请选择排查日期", trigger: "blur"}
        ],
        riskCheckPhase: [
          {required: true, message: '请选择排查阶段', trigger: 'blur'}
        ],
      },
      subDeptList: [],//运输企业
      riskListData: {
        riskCheckDate: new Date()
      },
      formData: {},
      riskPointType: [],//风险类型
      riskPointList: [],//排查清单
      riskCheckFile: {
        data: null,
        url: ''
      },
      riskCheckSignFile: {
        data: null,
        url: ''
      },
    }
  },
  beforeCreate() {//beforeCreate创建前状态

  },
  created() {//created创建完毕状态

  },
  beforeMount() {//beforeMount挂载前状态   DOM 元素然后塞入页面的过程

  },
  mounted() {//mounted 挂载结束状态
    var that = this;
    if (!!that.selectData.id) {

      that.axios.post(that.apiUrl.webApi + '/safety/risk/riskCheckInfo', {uuid: that.selectData.uuid}).then(res => {
        if (!!res) {


          var data = JSON.parse(JSON.stringify(res.data.data));
          data.riskCheckDate = new Date(data.riskCheckDate);
          delete data.createTime;
          delete data.detailList;

          that.riskListData = data;
          that.paiChaJieDuan();

          //排查清单
          that.axios.post(that.apiUrl.webApi + "/safety/risk/riskPointList", {riskPointTypeCode: data.riskPointTypeCode}).then(res => {
            if (!!res) {
              that.riskPointList = res.data.data;
            }
          }).catch(err => {
            console.log("失败", err)
          })

          that.riskCheckFile = {
            data: null,
            url: !!that.riskListData.riskCheckImg ? that.apiUrl.imgUrl + that.riskListData.riskCheckImg : ''
          };
          that.riskCheckSignFile = {
            data: null,
            url: !!that.riskListData.riskCheckSignImg ? that.apiUrl.imgUrl + that.riskListData.riskCheckSignImg : ''
          };

        }
      }).catch(err => {
        console.log("失败", err)
      })

    }

    //风险类型
    that.axios.post(that.apiUrl.systemDictSystemDictList, {type: "risk_point_type"}).then(res => {
      if (!!res) {
        that.riskPointType = res.data.data;
      }
    }).catch(err => {
      console.log("失败", err)
    })


    //运输企业
    that.axios.post(that.apiUrl.coreDeptCoreDeptList, {}).then(res => {
      if (!!res) {
        that.subDeptList = res.data.data;
        if (!that.selectData.id) {
          that.riskListData.deptUuid = that.subDeptList[0].uuid;
        }
      }
    }).catch(err => {
      console.log("失败", err)
    })


  },
  methods: {//执行的方法
    //风险状态
    riskTypeFun(data, type, num) {
      var that = this;
      if (type == 0) {//无隐患 清除
        that.riskListDetailEntityList[num].dangerDescribe = '';//发现问题，问题描述
        that.riskListDetailEntityList[num].riskItemCheckState = 0;
      } else {//有风险 弹框
        var data = JSON.parse(JSON.stringify(that.riskListDetailEntityList[num]))
        data.dangerDescribe = that.riskListDetailEntityList[num].dangerDescribe;
        data.num = num;
        that.formData = data;
        that.riskListDetailEntityList[num].riskItemCheckState = 1;
        that.riskType = true;
      }
    },
    riskCheckFileFun(file) {//营业执照图片
      let that = this;
      let type = file.type.split("/")[0];
      if (type == "image") {//图片
        that.riskCheckFile.url = window.URL.createObjectURL(file);
        that.riskCheckFile.data = file;
      } else {
        that.$Message.warning('请选择jpg、png、jpeg的图片进行上传');
      }
      return false;
    },
    riskCheckSignFileFun(file) {//营业执照图片
      let that = this;
      let type = file.type.split("/")[0];
      if (type == "image") {//图片
        that.riskCheckSignFile.url = window.URL.createObjectURL(file);
        that.riskCheckSignFile.data = file;
      } else {
        that.$Message.warning('请选择jpg、png、jpeg的图片进行上传');
      }
      return false;
    },
    //提交表单
    addSubmit() {
      let that = this;
      var data = JSON.parse(JSON.stringify(that.riskListData));
      data.riskCheckDate = that.public.timeFormatting(data.riskCheckDate, "yyyy-MM")
      let formData = new FormData();
      for (let key in data) {
        if (!!data[key]) {
          formData.append(key, data[key]);
        }
      }
      //检查照片
      if (!!that.riskCheckFile.data) {//选择了图片
        formData.append('riskCheckFile', that.riskCheckFile.data);
      }
      //签字照片
      if (!!that.riskCheckSignFile.data) {//选择了图片
        formData.append('riskCheckSignFile', that.riskCheckSignFile.data);
      }

      that.axios.post(that.apiUrl.webApi + "/safety/risk/riskCheckSaveOrUpdate", formData, that.public.parameterUploadProgress(that)).then(res => {
        that.$Spin.hide();
        if (!!res) {
          that.$Message.success("保存成功");
          that.$emit("closeFun", true)
        }
      }).catch(err => {
        console.log('失败', err);
      })
    },
    //隐患上传图片
    reportImgUrlFun(file) {
      var that = this;
      var type = file.type.split("/")[0];
      if (type == "image") {//图片
      } else {
        that.$Message.warning('请选择jpg、png、jpeg的图片进行上传');
      }
      return false;
    },
    riskPointNameFun(data) {
      var that = this;
      if (!!data) {
        that.riskListData.riskPointTypeName = data.label;
        that.locationFebruary();
      } else {
        that.riskListData.riskPointTypeName = '';
        that.riskPointList = [];
      }
    },
    //排查清单 加载
    locationFebruary(){
      var that = this;
      that.riskPointList = [];
      that.riskListData.riskPointUuid = '';


      that.riskListData.riskCheckCycle = '';
      that.riskListData.riskCheckPerson = '';
      that.riskCheckPhaseList = [];
      that.riskListData.riskCheckPhase = '';

      if(!!that.riskListData.deptUuid && !!that.riskListData.riskPointTypeCode){
        that.axios.post(that.apiUrl.webApi + "/safety/risk/riskPointList", {riskPointTypeCode: that.riskListData.riskPointTypeCode,deptUuid:that.riskListData.deptUuid}).then(res => {
          if (!!res) {
            that.riskPointList = res.data.data;
          }
        }).catch(err => {
          console.log("失败", err)
        })
      }
    },
    riskCheckCycleFun(data) {
      var that = this;
      if (!!data) {
        that.riskListData.riskCheckCycle = data ? that.riskPointList.find(ele => ele.uuid === data.value).riskPointCycle : ''
        that.riskListData.riskCheckPerson = data ? that.riskPointList.find(ele => ele.uuid === data.value).riskPointPerson : ''
        that.paiChaJieDuan();
      } else {
        that.riskListData.riskCheckCycle = '';
        that.riskListData.riskCheckPerson = '';
        that.riskCheckPhaseList = [];
        that.riskListData.riskCheckPhase = '';
      }
    },
    paiChaJieDuan(){
      var that = this;
      //排查周期  排查周期（0：不限，1：每天，2：每周，3：每旬，4：每月，5：每季）
      var riskCheckPhaseList = [];
      if(!that.selectData.id){
        that.$set(that.riskListData, 'riskCheckPhase', '')//全部数据
      }
      if(that.riskListData.riskCheckCycle == 0 || that.riskListData.riskCheckCycle == 1){
        var curDate = new Date();
        /* 获取当前月份 */
        var curMonth = curDate.getMonth();
        /*  生成实际的月份: 由于curMonth会比实际月份小1, 故需加1 */
        curDate.setMonth(curMonth + 1);
        if(!that.selectData.id){
          /* 将日期设置为0, 这里为什么要这样设置, 我不知道原因, 这是从网上学来的 */
          that.riskListData.riskCheckPhase = curDate.getDate()+'日';
        }
        curDate.setDate(0);
        /* 返回当月的天数 */
        for(var i =0;i<curDate.getDate();i++){
          riskCheckPhaseList.push((i+1)+'日')
        }
        //
      }else if(that.riskListData.riskCheckCycle == 4){
        for(var i =0;i<12;i++){
          riskCheckPhaseList.push((i+1)+"月")
        }
        if(!that.selectData.id){
          that.riskListData.riskCheckPhase = (new Date().getMonth()+1)+"月";
        }
      }else if(that.riskListData.riskCheckCycle == 2){
        function getWeeks() {
          var d = new Date();
          var year = d.getFullYear();
          var month = d.getMonth() + 1;

          // 该月第一天
          d.setFullYear(year, month-1, 1);
          var w1 = d.getDay();
          if (w1 == 0){
            w1 = 7;
          }
          // 该月天数
          d.setFullYear(year, month, 0);
          var dd = d.getDate();
          // 第一个周一
          let d1;
          if (w1 != 1){//第一天不是星期一
            d1 = 7 - w1 + 2;
          }else{
            d1 = 1;
          }
          let week_count = Math.ceil((dd-d1+1)/7);
          if(w1 == 1){//我的处理
            return week_count;
          }else{
            return week_count+1;
          }
        }
        for(var i =0;i<getWeeks();i++){
          riskCheckPhaseList.push("第"+(i+1)+"周")
        }
        function getMonthWeek(a, b, c) {
          var date = new Date(a, parseInt(b) - 1, c), w = date.getDay(), d = date.getDate();
          return Math.ceil(
            (d + 6 - w) / 7
          );
        };
        var last = new Date();//获取当前月最后一天时间
        var y = last.getYear();
        var m = last.getMonth() + 1;
        var d = last.getDate();
        if(!that.selectData.id){
          that.riskListData.riskCheckPhase = "第"+(getMonthWeek(y, m, d))+"周";
        }
      }else if(that.riskListData.riskCheckCycle == 3){
        riskCheckPhaseList = ['上旬','中旬','下旬'];
        if(!that.selectData.id){
          if(parseInt((new Date().getDate() - 1) / 10) == 0){
            that.riskListData.riskCheckPhase = '上旬';
          }else if(parseInt((new Date().getDate() - 1) / 10) == 1){
            that.riskListData.riskCheckPhase = '中旬';
          }else if(parseInt((new Date().getDate() - 1) / 10) == 2){
            that.riskListData.riskCheckPhase = '下旬';
          }
        }
      }else if(that.riskListData.riskCheckCycle == 5){
        for(var i =0;i<4;i++){
          riskCheckPhaseList.push("第"+(i+1)+"季度")
        }
        if(!that.selectData.id){
          that.riskListData.riskCheckPhase = "第"+(parseInt((new Date().getMonth()) / 3)+1)+"季度";
        }
      }
      that.riskCheckPhaseList = riskCheckPhaseList;
    },
  },
  watch: {//监听

  },
  beforeUpdate() {//beforeUpdate 更新前状态

  },
  updated() {//updated 更新完成状态

  },
  beforeDestroy() {//beforeDestroy 销毁前状态

  },
  destroyed() {//destroyed 销毁完成状态

  }
}
</script>
<style lang="less">
._wz_hiddenDangersTroubleshootAdd {
  overflow: auto;
  height: 100%;

  .demo-upload-list {
    display: inline-block;
    width: 120px;
    height: 80px;
    text-align: center;
    line-height: 80px;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
    position: relative;
    border: 1px solid rgba(0, 0, 0, .2);
    margin-right: 4px;

    img {
      width: 100%;
      height: 100%;
    }

    .demo-upload-list-cover {
      display: none;
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      background: rgba(0, 0, 0, .6);

      i {
        color: #fff;
        font-size: 20px;
        cursor: pointer;
        margin: 0 2px;
      }
    }
  }

  .demo-upload-list:hover .demo-upload-list-cover {
    display: block;
  }
}
</style>
